package com.mr.qa.action.check;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import com.mr.qa.GlobalConfigs;
import com.mr.qa.bo.User;
import com.mr.qa.dao.impl.UserDAO;

public class DailyDownloadSharedFileCheck implements DailyCheck {
	
	public static HashMap userDownloadSize;
    public static String recordDateString;//yyyy-mm-dd

	public boolean check(int userId) {
		UserDAO userDAO = new UserDAO();
		User user = userDAO.findById(userId);
		if (user.getUserScore().getTotalScore() < GlobalConfigs.NUMBER_SHARED_FILE_A_USER_DOWNLOAD_LIMIT_SCORE) {
			if (userDownloadSize == null || userDownloadSize.size() == 0)
				return true;
			Integer number = (Integer) userDownloadSize.get(userId);
			if (number != null
					&& number >= GlobalConfigs.NUMBER_SHARED_FILE_A_USER_DOWNLOAD_ONE_DAY)
				return false;

			return true;
		}
		return true;
	}

	public void init(int userId) {
		Date calendar = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = dateFormat.format(calendar);
        boolean ifNewRecord = false;
        if(!dateString.equals(recordDateString) || recordDateString == null)
        {
            ifNewRecord = true;
        }
        if(ifNewRecord)
        {
        	userDownloadSize = new HashMap();
            recordDateString = dateString;
            userDownloadSize.put(userId,0);
        }
	}

	public boolean update(int userId) {
		UserDAO userDAO = new UserDAO();
		User user = userDAO.findById(userId);
		if (user.getUserScore().getTotalScore() < GlobalConfigs.NUMBER_SHARED_FILE_A_USER_DOWNLOAD_LIMIT_SCORE) {
			Date calendar = new Date();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			String dateString = dateFormat.format(calendar);
			boolean ifNewRecord = false;
			if (!dateString.equals(recordDateString) || recordDateString == null) {
				ifNewRecord = true;
			}
			if (ifNewRecord || userDownloadSize == null) {
				userDownloadSize = new HashMap();
				recordDateString = dateString;
				userDownloadSize.put(userId, 1);
			} else {
				Integer number = (Integer) userDownloadSize.get(userId);
				if (number == null) {
					userDownloadSize.put(userId, 1);
				} else {
					if (number >= GlobalConfigs.NUMBER_SHARED_FILE_A_USER_DOWNLOAD_LIMIT_SCORE)
						return false;
					else {
						userDownloadSize.put(userId, number + 1);
					}
				}
			}
			return true;
		}
		return true;
	}

}
